import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { Observable } from 'rxjs';
import { PERMISSION_KEY } from 'src/common/decorator/permission.decorator'
@Injectable()
export class PermissionGuard implements CanActivate {
    @Inject()
    private readonly reflector: Reflector

    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
        const request: Request = context.switchToHttp().getRequest();
        if (!request.user) return true

        const permissions = request.user.permissions

        const requiredPermissions = this.reflector.getAllAndOverride<string[]>(PERMISSION_KEY.permission, [context.getClass(), context.getHandler()])
        if (!requiredPermissions) return true

        requiredPermissions.forEach(item => {
            const found = permissions.find(permission => permission.code === item);
            if (!found) throw new UnauthorizedException('您没有访问该接口的权限');
        })

        return true;
    }
}
